import { defineComponent, SetupContext, watch, ref, computed, toRefs, Ref, onMounted, onUnmounted, getCurrentInstance } from 'vue';
import { fileSelectProps, FileSelectProps } from './sub-component.props';
import { Subscription } from 'rxjs';

export default defineComponent({
    name: 'FFileSelect',
    props: fileSelectProps,
    emits: ['change'],
    setup(props: FileSelectProps, context: SetupContext) {
        // 附件上传元素
        const instance = getCurrentInstance();
        let $uploadInput: any;
        const {disabled } = toRefs(props);

        const onChange = () => {
            if ($uploadInput.files) {
                context.emit("change",$uploadInput.files);
                $uploadInput.value = null;
            }
        };

        watch(disabled, () => {
            bindEvent();
        });
        /**
         * 绑定事件
         */
        const bindEvent=()=>{
            if (disabled.value) {
                $uploadInput.removeEventListener('change', onChange);
            } else {
                $uploadInput.addEventListener('change', onChange);
            }
        }
        /**
         * 重置
         */
        const selectFile = () => {
            $uploadInput.click();
        };

        /**
         * 注册一个回调函数，在组件挂载完成后执行。
         */
        onMounted(() => {
            $uploadInput = instance?.proxy?.$refs.uploadInput as HTMLElement;
            bindEvent();
        });

        /**
         * 注册一个回调函数，在组件实例被卸载之后调用。
         */
        onUnmounted(() => { });

        return () => (
            <>
                <input
                    ref="uploadInput"
                    type="file"
                    class="ffileupload--browser"
                    disabled={disabled.value}
                    multiple={props.enableMulti}
                    accept={props.accept}
                    style="width: 10px"
                />
                <div
                    class={['upload-container', disabled.value ? 'f-state-disabled' : '']}
                    onClick={(ev: MouseEvent) => selectFile()}
                    title={props.selectText}>
                    <i class="f-icon f-icon-upload upload-icon" style="top: 2px;position: relative;"></i>{props.selectText}
                </div>
            </>
        );
    }
});
